package com.rickpan.controller;

import com.rickpan.service.UserOnlineService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户在线状态控制器
 * 
 * @author RickPan Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/users/online")
@Tag(name = "用户在线状态", description = "用户在线状态管理API")
public class UserOnlineController {

    @Autowired
    private UserOnlineService userOnlineService;

    /**
     * 获取在线用户列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取在线用户列表", description = "获取当前所有在线用户的信息")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER')")
    public ResponseEntity<Map<String, Object>> getOnlineUsers() {
        try {
            List<Map<String, Object>> onlineUsers = userOnlineService.getOnlineUsers();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", onlineUsers);
            response.put("totalCount", onlineUsers.size());
            response.put("message", "获取在线用户列表成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取在线用户列表失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取在线用户数量
     */
    @GetMapping("/count")
    @Operation(summary = "获取在线用户数量", description = "获取当前在线用户的总数量")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER')")
    public ResponseEntity<Map<String, Object>> getOnlineUserCount() {
        try {
            long count = userOnlineService.getOnlineUserCount();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", count);
            response.put("message", "获取在线用户数量成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取在线用户数量失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 检查指定用户是否在线
     */
    @GetMapping("/check/{userId}")
    @Operation(summary = "检查用户在线状态", description = "检查指定用户是否在线")
    @PreAuthorize("hasRole('ADMIN') or hasRole('USER')")
    public ResponseEntity<Map<String, Object>> checkUserOnline(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            boolean isOnline = userOnlineService.isUserOnline(userId);
            Map<String, Object> userStatus = userOnlineService.getUserStatus(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", Map.of(
                "userId", userId,
                "isOnline", isOnline,
                "status", userStatus
            ));
            response.put("message", "检查用户在线状态成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "检查用户在线状态失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户的所有会话
     */
    @GetMapping("/sessions/{userId}")
    @Operation(summary = "获取用户会话列表", description = "获取指定用户的所有活跃会话")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getUserSessions(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            List<Map<String, Object>> sessions = userOnlineService.getUserSessions(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", sessions);
            response.put("totalCount", sessions.size());
            response.put("message", "获取用户会话列表成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取用户会话列表失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 强制用户下线（管理员功能）
     */
    @PostMapping("/force-offline/{userId}")
    @Operation(summary = "强制用户下线", description = "管理员强制指定用户下线")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> forceUserOffline(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            userOnlineService.forceUserOffline(userId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "用户已强制下线");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "强制用户下线失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 清理超时用户（管理员功能）
     */
    @PostMapping("/cleanup-timeout")
    @Operation(summary = "清理超时用户", description = "管理员手动清理超时的在线用户")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> cleanupTimeoutUsers() {
        try {
            userOnlineService.cleanupTimeoutUsers();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "超时用户清理完成");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "清理超时用户失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取在线状态统计信息（管理员功能）
     */
    @GetMapping("/stats")
    @Operation(summary = "获取在线状态统计", description = "获取在线用户的统计信息")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<Map<String, Object>> getOnlineStats() {
        try {
            List<Map<String, Object>> onlineUsers = userOnlineService.getOnlineUsers();
            long totalCount = userOnlineService.getOnlineUserCount();
            
            // 统计不同状态的用户数量
            long activeCount = onlineUsers.stream()
                .mapToLong(user -> (Boolean) user.get("isOnline") ? 1 : 0)
                .sum();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalOnlineUsers", totalCount);
            stats.put("activeUsers", activeCount);
            stats.put("timestamp", System.currentTimeMillis());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            response.put("message", "获取在线状态统计成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取在线状态统计失败: " + e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
}
